# coding:utf-8

import random
import cv2
import tensorflow as tf
import numpy as np
from PIL import Image


class TFImageProcess:
    def __init__(self, sess=None, error_level=0):
        if not sess:
            self.sess = tf.Session()
        else:
            self.sess = sess
        self.error_level = error_level

    def run(self, inputs):
        try:
            return self.sess.run(inputs)
        except:
            if self.error_level == 0:
                raise RuntimeError("maybe some error in inputs")

    def save(self, tensor, path, scale=False):
        img = self.sess.run(tensor)
        if scale:
            img *= 255

        cv2.imwrite(path, img)

    @staticmethod
    def open(path):
        try:
            img_raw = tf.gfile.FastGFile(path, "rb").read()

            image = tf.image.decode_image(img_raw)
        except:
            return None

        return image

    @staticmethod
    def open_using_opencv(path, flag=1):
        image = cv2.imread(path, flag)

        try:
            image_tensor = tf.convert_to_tensor(image)
        except:
            return None

        return image_tensor

    @staticmethod
    def open_using_pillow(path):

        image = Image.open(path)

        try:
            image_tensor = tf.convert_to_tensor(np.array(image))
        except:
            return None
        return image_tensor


class CVImageProcess:
    def __init__(self):
        self.gamma_tabel = None

    @staticmethod
    def noise(image, npts=50):
        height, width = image.shape[:2]
        for idx in range(npts):
            x = random.randint(0, width - 1)
            y = random.randint(0, height - 1)
            pix = random.choice([0, 255])
            image[y, x, :] = [pix, pix, pix]

        return image

    def init_gamma_tabel(self, gamma):
        gamma_tabel = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]
        self.gamma_tabel = np.round(np.array(gamma_tabel).astype(np.uint8))

    def gamma(self, image):
        return cv2.LUT(image, self.gamma_tabel)


if __name__ == '__main__':
    tfimg = TFImageProcess(error_level=0)
    image = tfimg.open("/Users/ding/haha.png")
    # image = tfimg.open_using_opencv("/home/ding/models/datas/back.jpg")

    img = tfimg.run(image)
    print(img.shape)

    # cv2.namedWindow("show")
    # cv2.imshow("show", img)
    # cv2.waitKey()
    # cv2.destroyAllWindows()
    tfimg.save(image, "a.png", False)

    #
    # image = tfimg.open_using_pillow("/home/ding/models/datas/back.jpg")
    #
    # print(image.shape, type(image))
    # img = tfimg.run(image)
    #
    # img = CVImageProcess.noise(img, 10000)
    #
    # proc = CVImageProcess()
    # proc.init_gamma_tabel(0.4)
    #
    # img = proc.gamma(img)
    #
    # cv2.namedWindow("show")
    # cv2.imshow("show", img)
    # cv2.waitKey()
    # cv2.destroyWindow("show")
    t = TxtImgGen(["/Users/ding/datas/idcard/0.lst"], ["/Users/ding/datas/idcard/font/font.lst"], [25, 26, 25, 29, 30, 38])

    for i in range(30):
        t.gen_font()
        t.gen_color([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]])
        img_crp = t.crop_text_line(u"中 国人民共和国", enlarge=1, shack=[[-10, -5], [0, 0], [5, 10], [0, 0]])
        img_crp.show()

    # print(TxtGen.gen_dict_text([2, 10]))
    # t = TxtGen()
    # t.read_from_file(["/Users/ding/Downloads/姓名/normal_name.txt"])
    # texts = t.gen_text(10)
    # texts = t.gen_nation(10)
    #
    # for text in texts:
    #     text = t.gen_pank_name()
    #     img_crp = tim.crop_text_line(text, enlarge=1)
    #     img_crp.show()
